package com.bom_samaritano.repositorio;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import android.content.Context;
import android.os.Debug;

import com.bom_samaritano.Exception.BusinessException;
import com.bom_samaritano.dao.DAO;
import com.bom_samaritano.dao.DataAdapter;
import com.bom_samaritano.model.Person;
import com.bom_samaritano.model.Route;
import com.bom_samaritano.model.VOGeneric;
import com.bom_samaritano.temp.LatLng;
import com.bom_samaritano.util.Constantes;

public class RepositorioUsuarioSQlite implements IRepositorioUsuario {

	private static RepositorioUsuarioSQlite aRepositorioUsuarioSQlite;
	private static DAO<VOGeneric> dao;

	public static IRepositorioUsuario getInstance(Context context) {
		if (aRepositorioUsuarioSQlite == null) {
			aRepositorioUsuarioSQlite = new RepositorioUsuarioSQlite();
			dao = DataAdapter.getInstance(context);
		}
		return aRepositorioUsuarioSQlite;
	}

	@Override
	public void cadastrarUsuario(Person usuario) {
		dao.insert(usuario);
	}

	@Override
	public void atualizarUsuario(Person usuario) {
		dao.update(usuario, usuario.getIdUsuario());
	}

	@Override
	public void deletarUsuario(Person usuario) {
		dao.delete(usuario);

	}

	@Override
	public void cadastrarRota(Route route) {
		System.out.println("inserir rota");
		dao.insert(route);
	}

	@Override
	public void alterarRota(Route route) {
		dao.update(route, route.getId());
	}

	@Override
	public void deletarRota(Route route) {
		dao.delete(route);
	}

	@Override
	public Collection<Person> getAll() throws BusinessException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Collection<VOGeneric> getDadosRota(LatLng start, LatLng end)
			throws BusinessException {

		List<LatLng> points = new ArrayList<LatLng>();
		points.add(start);
		points.add(end);

		Collection<Route> routes = dao.dataRoute(null);
		Collection<VOGeneric> retorno = new ArrayList<VOGeneric>();
		boolean isRotaCompativel;
		for (Route iRoute : routes) {
			// Adiciona ao retorno a rota seguido do dono
			isRotaCompativel = iRoute.getPoints().containsAll(points);
			System.out.println("isRotaCompativel: " + isRotaCompativel);
			System.out.println("iRoute: " + iRoute);
			System.out.println("points: " + points);
			if (!isRotaCompativel) {
				// retorno.add(iRoute);
				continue;
			}
			retorno.add(iRoute);
		}
		return retorno;

	}

	@Override
	public Person getPerson(String login) {
		Collection<VOGeneric> voGenerics = dao.select(Person.TABLE,
				new String[] { Person.COL_LOGIN, Person.COL_SENHA });

		for (VOGeneric vo : voGenerics) {
			Person p = new Person();
			p.setLogin(vo.getParam(Person.COL_LOGIN).toString());
			p.setSenha(vo.getParam(Person.COL_SENHA).toString());

			if (login.equalsIgnoreCase(p.getLogin())) {
				return p;
			}

		}

		return null;
	}
}
